# -*- coding: utf-8 -*-
import argparse
import hashlib
import hmac
import json
import sys
import time
from datetime import datetime, timezone

if sys.version_info[0] <= 2:
    from httplib import HTTPSConnection
else:
    from http.client import HTTPSConnection


def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()

def readfile(file_path):
    with open(file_path, 'r') as file:
        # 读取文件内容
        content = file.read()
    return content

def main(secret_id,secret_key,domain, cert,cert_key):
    secret_id = secret_id
    secret_key = secret_key
    token = ""
    service = "cdn"
    host = "cdn.tencentcloudapi.com"
    region = ""
    version = "2018-06-06"
    action = "UpdateDomainConfig"
    # print(cert)
    params = {"Domain":f"{domain}",
              "HttpsBilling":{"Switch":"on"},
              "Https":{"Switch":"on",#"Http2":"off","OcspStapling":"off","VerifyClient":"off",
                       "CertInfo":{"Certificate":f"{cert}","PrivateKey":f"{cert_key}"}
                       }
              }
    # print(params["Https"]["CertInfo"]["Certificate"])
    payload = json.dumps(params)
    # print(payload)
    endpoint = "https://cdn.tencentcloudapi.com"
    algorithm = "TC3-HMAC-SHA256"
    timestamp = int(time.time())
    date = datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%Y-%m-%d")

    # ************* 步骤 1：拼接规范请求串 *************
    http_request_method = "POST"
    canonical_uri = "/"
    canonical_querystring = ""
    ct = "application/json; charset=utf-8"
    canonical_headers = "content-type:%s\nhost:%s\nx-tc-action:%s\n" % (ct, host, action.lower())
    signed_headers = "content-type;host;x-tc-action"
    hashed_request_payload = hashlib.sha256(payload.encode("utf-8")).hexdigest()
    canonical_request = (http_request_method + "\n" +
                         canonical_uri + "\n" +
                         canonical_querystring + "\n" +
                         canonical_headers + "\n" +
                         signed_headers + "\n" +
                         hashed_request_payload)

    # ************* 步骤 2：拼接待签名字符串 *************
    credential_scope = date + "/" + service + "/" + "tc3_request"
    hashed_canonical_request = hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()
    string_to_sign = (algorithm + "\n" +
                      str(timestamp) + "\n" +
                      credential_scope + "\n" +
                      hashed_canonical_request)

    # ************* 步骤 3：计算签名 *************
    secret_date = sign(("TC3" + secret_key).encode("utf-8"), date)
    secret_service = sign(secret_date, service)
    secret_signing = sign(secret_service, "tc3_request")
    signature = hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()

    # ************* 步骤 4：拼接 Authorization *************
    authorization = (algorithm + " " +
                     "Credential=" + secret_id + "/" + credential_scope + ", " +
                     "SignedHeaders=" + signed_headers + ", " +
                     "Signature=" + signature)

    # ************* 步骤 5：构造并发起请求 *************
    headers = {
        "Authorization": authorization,
        "Content-Type": "application/json; charset=utf-8",
        "Host": host,
        "X-TC-Action": action,
        "X-TC-Timestamp": timestamp,
        "X-TC-Version": version
    }
    if region:
        headers["X-TC-Region"] = region
    if token:
        headers["X-TC-Token"] = token

    try:
        req = HTTPSConnection(host)
        req.request("POST", "/", headers=headers, body=payload.encode("utf-8"))
        resp = req.getresponse().read()
        msg = json.loads(resp)
        print(msg)
        if msg["Response"].get("Error", False):
            return 1

        return 0
    except Exception as err:
        print(err)
        return 1

if __name__ == "__main__":
    description = """Tencent API command-line tool"""

    epilog = """Examples:"""

    parser = argparse.ArgumentParser(description=description, epilog=epilog,
                                     formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('-i', '--secret-id', action='store', dest='secret_id', required=True,
                        help="secret_id")
    parser.add_argument('-s', '--secret-key', action='store', dest='secret_key', required=True,
                        help="secret_key")
    parser.add_argument('-d', '--domain', action='store', dest='domain', required=True,
                        help='domain name')
    parser.add_argument('-c', '--cert-file', action='store', dest='certfile', required=True,
                        help='cert file name')
    parser.add_argument('-k', '--key-file', action='store', dest='keyfile', required=True,
                        help='cert key file name')

    args = parser.parse_args()

    aKeyId = args.secret_id
    aKey = args.secret_key

    domain = args.domain
    certFile = readfile(args.certfile)
    keyFile = readfile(args.keyfile)

    retv = main(aKeyId,aKey,domain,certFile,keyFile)

    sys.exit(retv)
